﻿using CloudMusic.Helper;
using CloudMusic.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace CloudMusic.ViewModel
{
    /// <summary>
    /// 歌单详情viewmodel
    /// </summary>
    public class PageSongSheetDetailViewModel : MusicViewModelBase
    {
        public PageSongSheetDetailViewModel()
        {

        }

        #region 定义
        private long Id;
        /// <summary>
        /// 副标题是否出现
        /// </summary>
        private Visibility subVIS = Visibility.Collapsed;
        /// <summary>
        /// 歌曲性质列表
        /// </summary>
        List<PrivilegesItem> privilegesItems = null;
        /// <summary>
        /// 音乐列表
        /// </summary>
        private ObservableCollection<MusicModel> songSheetList;
        public ObservableCollection<MusicModel> SongSheetList
        {
            get
            {
                if (songSheetList == null)
                {
                    songSheetList = new ObservableCollection<MusicModel>();
                }
                return songSheetList;
            }
            set
            {
                songSheetList = value;
                OnPropertyChanged("SongSheetList");
            }
        }
        /// <summary>
        /// 歌单封面
        /// </summary>
        private string cover;
        public string Cover
        {
            get
            { return cover; }
            set
            {
                cover = value;
                OnPropertyChanged("Cover");
            }
        }
        /// <summary>
        /// 歌单名字
        /// </summary>
        private string songName;
        public string SongName
        {
            get
            {
                return songName;
            }
            set
            {
                songName = value;
                OnPropertyChanged("SongName");
            }
        }
        /// <summary>
        /// 歌曲数量
        /// </summary>
        private Int64 songCount = 0;
        public Int64 SongCount
        {
            get
            {
                return songCount;
            }
            set
            {
                songCount = value;
                OnPropertyChanged("SongCount");
            }
        }
        /// <summary>
        /// 播放数量
        /// </summary>
        private string playCount = "0";
        public string PlayCount
        {
            get
            {
                return playCount;
            }
            set
            {
                playCount = value;
                OnPropertyChanged("PlayCount");
            }
        }
        /// <summary>
        /// 作者头像
        /// </summary>
        private string authorImgUrl;
        public string AuthorImgUrl
        {
            get
            {
                return authorImgUrl;
            }
            set
            {
                authorImgUrl = value;
                OnPropertyChanged("AuthorImgUrl");
            }
        }
        /// <summary>
        /// 作者名字
        /// </summary>
        private string authorName;
        public string AuthorName
        {
            get
            {
                return authorName;
            }
            set
            {
                authorName = value;
                OnPropertyChanged("AuthorName");
            }
        }
        /// <summary>
        /// 创建时间
        /// </summary>
        private string creatTime;
        public string CreatTime
        {
            get
            {
                return creatTime;
            }
            set
            {
                creatTime = value;
                OnPropertyChanged("CreatTime");
            }
        }
        /// <summary>
        /// 收藏数量
        /// </summary>
        private Int64 collectionCount = 0;
        public Int64 CollectionCount
        {
            get
            {
                return collectionCount;
            }
            set
            {
                collectionCount = value;
                OnPropertyChanged("CollectionCount");
            }
        }
        /// <summary>
        /// 分享次数
        /// </summary>
        private Int64 shareCount = 0;
        public Int64 ShareCount
        {
            get
            {
                return shareCount;
            }
            set
            {
                shareCount = value;
                OnPropertyChanged("ShareCount");
            }
        }
        /// <summary>
        /// 标签
        /// </summary>
        private string strLable;
        public string StrLable
        {
            get
            {
                return strLable;
            }
            set
            {
                strLable = value;
                OnPropertyChanged("StrLable");
            }
        }
        /// <summary>
        /// 歌单简介
        /// </summary>
        private string strIntroduction;
        public string StrIntroduction
        {
            get
            {
                return strIntroduction;
            }
            set
            {
                strIntroduction = value;
                OnPropertyChanged("StrIntroduction");
            }
        }
        /// <summary>
        /// 评论数量
        /// </summary>
        private string commCount = "评论";
        public string CommCount
        {
            get
            {
                return commCount;
            }
            set
            {
                commCount = value;
                OnPropertyChanged("CommCount");
            }
        }
        /// <summary>
        /// 
        /// </summary>
        public int width;
        public int Width
        {
            get { return width; }
            set { width = value; OnPropertyChanged("Width"); }
        }
        private int usertype;
        public int userType
        {
            get { return usertype; }
            set { usertype = value;OnPropertyChanged("userType"); }
        }
        #endregion

        public PageSongSheetDetailViewModel(long id,int hq)
        {
            Width = 80;
            try
            {
                Task.Run(async () =>
                {
                    var strJosn = CommonHelper.Get("http://localhost:3000/playlist/detail?id=" + id);// CommonHelper.Get("http://localhost:3000/playlist/detail?id=" + id);
                    if (strJosn == "") return;
                    JObject obj = (JObject)JsonConvert.DeserializeObject(strJosn);
                    Cover = obj["playlist"]["coverImgUrl"].ToString();
                    SongName = obj["playlist"]["name"].ToString();
                    SongCount = (long)obj["playlist"]["trackCount"];
                    PlayCount = CommonHelper.toNumber(obj["playlist"]["playCount"].ToString());
                    string AvatarUrl = obj["playlist"]["creator"].ToString();
                    JObject Data = (JObject)JsonConvert.DeserializeObject(AvatarUrl);
                    AuthorImgUrl = Data["avatarUrl"].ToString();
                    AuthorName = Data["nickname"].ToString();
                    userType = Convert.ToInt16(Data["userType"]);
                    CreatTime = DateTimeHelper.ConvertTimeStampToDateTime((long)obj["playlist"]["createTime"]).ToString("yyyy-MM-dd");
                    CollectionCount = (long)obj["playlist"]["subscribedCount"];
                    ShareCount = (long)obj["playlist"]["shareCount"];
                    List<string> tags = JsonConvert.DeserializeObject<List<string>>(JsonConvert.SerializeObject(obj["playlist"]["tags"]));
                    for (int i = 0; i < tags.Count; i++)
                    {
                        StrLable += tags[i] + "/";
                    }
                    if (StrLable != null && StrLable.Length > 0)
                    {
                        StrLable = StrLable.Substring(0, StrLable.Length - 1);
                    }
                    strIntroduction = obj["playlist"]["description"].ToString();
                    if (obj["playlist"]["commentCount"].ToString() != "")
                    {
                        CommCount = "评论(" + obj["playlist"]["commentCount"].ToString() + ")";
                    }
                    else
                    {
                        CommCount = "评论";
                    }
                    await Task.Run(() =>
                    {
                        List<TrackIdsItem> trackIds = JsonConvert.DeserializeObject<List<TrackIdsItem>>(JsonConvert.SerializeObject(obj["playlist"]["trackIds"]));
                        string[] re = new string[2];
                        if (trackIds.Count > 800)
                        {
                            List<SongsRoot> SR = new List<SongsRoot>();
                            for (int i = 0; i < trackIds.Count; i++)
                            {
                                if (i < 700)
                                {
                                    re[0] += trackIds[i].id.ToString() + ",";
                                }
                                else
                                {
                                    re[1] += trackIds[i].id.ToString() + ",";
                                }
                            }
                            for (int i = 0; i < re.Length; i++)
                            {
                                var strSongJosn = CommonHelper.Get("http://localhost:3000/song/detail?ids=" + re[i].Substring(0, re[i].Length - 1));
                                SongsRoot sr = JsonConvert.DeserializeObject<SongsRoot>(strSongJosn);
                                SetList(sr,id,hq);
                            }
                            //var strSongJosn_1 = CommonHelper.Get("http://localhost:3000/song/detail?ids=" + re[0].Substring(0, re[0].Length - 1));
                            //var strSongJosn_2 = CommonHelper.Get("http://localhost:3000/song/detail?ids=" + re[1].Substring(0, re[1].Length - 1));   
                            //var strSongJosn_3 = CommonHelper.ConvertStringToJson(str.ToString());
                            //SongsRoot sr = JsonConvert.DeserializeObject<SongsRoot>(strSongJosn_3);
                            //SetList(sr, id);

                        }
                        else
                        {
                            string ids = null;
                            string Id = null;
                            for (int i = 0; i < trackIds.Count; i++)
                            {
                                Id += trackIds[i].id + ",";
                            }
                            ids = Id.Substring(0, Id.Length - 1);
                            var sr = CommonHelper.GetEquipList<SongsRoot>(1, "http://localhost:3000/song/detail?ids=" + ids);
                            SetList(sr,id,hq);
                        }
                    });
                });
            }
            catch (Exception) { }
        }
        /// <summary>
        /// 歌单歌曲列表数据封装
        /// </summary>
        /// <param name="sr"></param>
        /// <param name="id"></param>
        private void SetList(SongsRoot sr,long id,int hq)
        {
            privilegesItems = new List<PrivilegesItem>();
            privilegesItems = sr.privileges;
            for (int i = 0; i < sr.songs.Count; i++)
            {
                for (int j = 0; j < privilegesItems.Count; j++)
                {
                    if (sr.songs[i].id == privilegesItems[j].id)
                    {
                        MusicModel data = new MusicModel
                        {
                            Index = i < 9 ? "0" + (i + 1).ToString() : i.ToString(),
                            Album = sr.songs[i].al.name,
                            AlbumId = sr.songs[i].al.id,
                            Name = sr.songs[i].name.Trim(),
                            Subtitle = GetSubtitle(sr.songs[i].alia),
                            Id = sr.songs[i].id,
                            CoverTitle = CommonHelper.GetTitle(sr.songs[i].name, sr.songs[i].alia),
                            Artist = sr.songs[i].ar[0].name,
                            SingerId = sr.songs[i].ar[0].id,
                            Type = 1,
                            PicUrl = sr.songs[i].al.picUrl,
                            SongId = id,
                            CanPlay = true,
                            TimeStr = DateTimeHelper.GetTime((sr.songs[i].dt / 1000).ToString()),
                            MVVis = CommonHelper.GetMvVis(sr.songs[i].mv),
                            VIPVis = CommonHelper.GetVis(privilegesItems[j].fee),
                            STVis = CommonHelper.GetVis(privilegesItems[j].fee),
                            SQVis = CommonHelper.GetVis(privilegesItems[j].maxbr),
                            Source = songName,
                            Pop = sr.songs[i].pop.ToString(),
                            ChargeInfoList =CommonHelper.GetChargeInfos(privilegesItems[j].chargeInfoList),
                            SubtitleVis = subVIS,
                            Playing = false,
                            HighQuality =hq,
                            Like = CommonHelper.CheckLikes(sr.songs[i].id)

                        };
                        //var data = EntityHelper.SetMusicModel(sr.songs[i], privilegesItems[j], id, songName, i);
                        // ObservableCollection类型-- - 该类型的 CollectionView 不支持从调度程序线程以外的线程对其 SourceCollection 进行的更改, 解决方案
                        ThreadPool.QueueUserWorkItem(delegate
                        {
                            SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(Application.Current.Dispatcher));
                            SynchronizationContext.Current.Post(pl =>
                            {
                                //里面写真正的业务内容
                                SongSheetList.Add(data);
                            }, null);
                        });
                    }
                }
            }
        }

        /// <summary>
        /// 副标题操作
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private string GetSubtitle(List<string> str)
        {
            subVIS = Visibility.Collapsed;
            string al = null;
            if (str.Count > 0)
            {
                for (int i = 0; i < str.Count; i++)
                {
                    al += "(" + str[i] + ")";
                }
                subVIS = Visibility.Visible;
            }
            return al;
        }
    }
}
